package com.studyspringcloud.order.control;

import com.studyspringcloud.order.config.RestTemplateConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@Slf4j
public class ClientController {

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    RestTemplate restTemplate;

    @GetMapping("getProductMsg")
    public String getProductMsg(){
//        1.第一种方式 缺点url 写死，无法适配位置IP，无法适配集群，负载均衡的服务
//        RestTemplate template = new RestTemplate();
//        String response = template.getForObject("http://localhost:8767/msg",String.class);
//        log.info("response="+response);
//        return response;

//        2第二种方法 适配负载均衡，但写法啰嗦
//        ServiceInstance instance = loadBalancerClient.choose("PRODUCT");
//        System.out.println(instance.getHost());
//        String url = "http://"+instance.getHost()+":"+instance.getPort()+"/msg";
//        RestTemplate template = new RestTemplate();
//        String response = template.getForObject(url,String.class);
//        log.info("response="+response);
//        return response;


        //3.第三种方法添加RestTemplateConfig类，并在方法中添加@LoadBalance @Bean注解
        String response = restTemplate.getForObject("http://PRODUCT/msg",String.class);
        log.info("response="+response);
        return response;

    }

}
